package com.ukefu.webim.util.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ukefu.webim.service.es.MRoundQuestionRepository;
import com.ukefu.webim.util.event.AiMRoundsProcesser;
import com.ukefu.webim.util.server.message.ChatMessage;
import com.ukefu.webim.web.model.AiUser;
import com.ukefu.webim.web.model.MRoundQuestion;

@Component
public class AiMRoundsReplyImpl extends AiMRoundsProcesser{
	
	@Autowired
	private MRoundQuestionRepository mRoundsQuestionRes ;

	@Override
	public ChatMessage process(AiUser aiUser , ChatMessage chat, String question) {
		ChatMessage retChatMessage = null , tempReplyMessage = null;
		if(aiUser!=null && !StringUtils.isBlank(aiUser.getBussid()) && !StringUtils.isBlank(chat.getMessage())) {
			List<MRoundQuestion> mRoundsQuestionList = mRoundsQuestionRes.findByDataidAndOrgi(aiUser.getDataid() , !StringUtils.isBlank(aiUser.getOrgi()) ? aiUser.getOrgi() : chat.getOrgi()) ;
			MRoundQuestion current = null , notMatch  = null ;
			for(MRoundQuestion mrq : mRoundsQuestionList) {
				/**
				 * 当前节点的 答案
				 */
				String content = chat.getMessage().replaceAll("[\\pP\\p{Punct}]", " ") ;
				try {
					if((!StringUtils.isBlank(mrq.getTitle()) && !StringUtils.isBlank(mrq.getParentid()) && mrq.getParentid().equals(aiUser.getBussid()) && !mrq.getParentid().equals(mrq.getId())) || ("0".equals(mrq.getParentid()))) {
						String title = mrq.getTitle().replaceAll("\\{([\\S\\s]*?),([\\S\\s]*?)\\}", "{$1<>$2}") ;
						String[] keywords = title.split("[,， ]") ;
						for(String keyword : keywords) {
							keyword = keyword.replaceAll("<>", ",") ;
							if(!StringUtils.isBlank(keyword) && (content.matches(keyword) || content.indexOf(keyword) >= 0)) {
								current = mrq ;
								break ;
							}
						}
						if(current!=null) break ;
					}
				}catch(Exception ex) {
					ex.printStackTrace();
				}
				if(mrq.getId().equals(aiUser.getBussid())) {
					notMatch = mrq ;
				}
			}
			if(current != null) {
				retChatMessage = syncReplayMessage(current , current.getContent() , chat , hasChilde(mRoundsQuestionList, current) == false, "nochild" , aiUser);
			}
			if(current == null || !"0".equals(current.getParentid())) {
				tempReplyMessage = super.exchange(aiUser , chat , current , notMatch , hasChildeNotRoot(mRoundsQuestionList, current!=null ? current : notMatch));
			}
			if(retChatMessage == null && aiUser.isInterrupt()) {
				retChatMessage = tempReplyMessage ;
			}
		}
		return retChatMessage ;
	}
}
